import {EventEmitter, Injectable} from '@angular/core';
import {Router} from "@angular/router";
import 'rxjs/add/operator/map';
import {Http} from "@angular/http";
import {TipService} from "./tip.service";
import {ExtendHttpService} from "../../common/extend-http.service";

@Injectable()
export class IndexService {

  // 所有分类菜品数据列表
  foodAll = [];


  // 数据发生变化的发射器
  foodAllEmit = new EventEmitter();

  // 桌子列表发射器
  tableListEmit = new EventEmitter();

  // tip状态
  tipType = 'error';

  constructor(private extendHttp: ExtendHttpService,
              private router: Router,
              private http: Http,
              private tipService: TipService
  ) {

    this.foodAllEmit.emit(this.foodAll);
  }

  // 获取数据
  getData() {
    return this.foodAll;
  }

  // 更新所有数据
  updateData(data){
    this.foodAll = data;
    this.foodAllEmit.emit(this.foodAll);
  }

  // 更新单个菜品数据
  updateItem(item) {

    this.foodAll.forEach(v=>{
      if (v.id == item.did) {
        v.foodList.forEach(v1=>{
          if (v1.id == item.id) {
            v1 = item;
            return;
          }
        });
        return;
      }
    });
  this.foodAllEmit.emit(this.foodAll);
  }

  // 清除购物车
  clearData() {
    this.foodAll.forEach(v => {
      v.count = 0;
      v.foodList.forEach(v1 => {
        v1.count = 0;
        v1.radioType = [];
        v1.multiType = [];
        v1.pumpType = [];
        v1.typeList.radioType = [];
        v1.typeList.multiType = [];
        v1.typeList.pumpType = [];
      });

    });
    this.foodAllEmit.emit(this.foodAll);
  }

  // 重新登录后清除数据
  emptyData() {
    this.foodAll = [];
  }

  // 进入index组件 CanActivate 调用方法
  requestData(): any {
    return this.extendHttp.get('/merchantApp/singleprocess/getDishesAndFood', {}).map(data => {
      let body = data.json();
      if (body.code == '0') {
        let tempArr = body['list'];


        // 分类和菜品添加count属性用于计数
        tempArr.forEach((v)=>{
          v.count = 0;
          v.foodList.forEach(v1=>{
            v1.count = 0;
            // 菜品添加类型列表属性，用于存储单选，多选，抽选的值
            v1['typeList'] = {radioType: [], multiType: [], pumpType: []}
          })
        });

        this.foodAll = tempArr;
        return true;
      } else if (body['code'] == '-2001') {
        this.router.navigateByUrl('/login');
      }  else {
        return false;
      }
    });
  }

}

